

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';
import { authAPI, setAuthToken } from '../../services/api';

interface LoginFormData {
  username: string;
  password: string;
  rememberMe: boolean;
}

const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  const [formData, setFormData] = useState<LoginFormData>({
    username: '',
    password: '',
    rememberMe: false
  });
  const [showPassword, setShowPassword] = useState<boolean>(false);
  const [showErrorMessage, setShowErrorMessage] = useState<boolean>(false);
  const [errorText, setErrorText] = useState<string>('用户名或密码错误，请重试');
  const [isLoading, setIsLoading] = useState<boolean>(false);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '食算 - 登录';
    return () => { document.title = originalTitle; };
  }, []);

  // 显示错误信息
  const showError = (message: string) => {
    setErrorText(message);
    setShowErrorMessage(true);
    setTimeout(() => {
      setShowErrorMessage(false);
    }, 5000);
  };

  // 隐藏错误信息
  const hideError = () => {
    setShowErrorMessage(false);
  };

  // 表单验证
  const validateForm = (): boolean => {
    const { username, password } = formData;

    if (!username.trim()) {
      showError('请输入邮箱或手机号');
      return false;
    }

    if (!password.trim()) {
      showError('请输入密码');
      return false;
    }

    // 邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    // 手机号格式验证（简单验证）
    const phoneRegex = /^1[3-9]\d{9}$/;

    if (!emailRegex.test(username) && !phoneRegex.test(username)) {
      showError('请输入正确的邮箱或手机号格式');
      return false;
    }

    if (password.length < 6) {
      showError('密码长度至少6位');
      return false;
    }

    hideError();
    return true;
  };

  // 处理输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;
    setFormData(prevData => ({
      ...prevData,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  // 处理密码显示/隐藏切换
  const handleTogglePassword = () => {
    setShowPassword(prevShow => !prevShow);
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setIsLoading(true);

    try {
      const response = await authAPI.login(formData.username, formData.password);
      
      // 保存token
      setAuthToken(response.token);
      
      // 跳转到首页
      navigate('/home');
    } catch (err: any) {
      showError(err.message || '登录失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 处理用户名输入框回车
  const handleUsernameKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      const passwordInput = document.querySelector('#password') as HTMLInputElement;
      if (passwordInput) {
        passwordInput.focus();
      }
    }
  };

  // 处理密码输入框回车
  const handlePasswordKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      const form = e.currentTarget.closest('form');
      if (form) {
        form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
      }
    }
  };

  // 处理输入框焦点事件
  const handleInputFocus = () => {
    hideError();
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 主容器 */}
      <div className="w-full max-w-md">
        {/* Logo和产品名称区域 */}
        <div className={`text-center mb-8 ${styles.logoAnimation}`}>
          <div className="w-16 h-16 bg-primary rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-card">
            <i className="fas fa-utensils text-white text-2xl"></i>
          </div>
          <h1 className="text-3xl font-bold text-text-primary mb-2">食算</h1>
          <p className="text-text-secondary">智能饮食管理，健康生活助手</p>
        </div>

        {/* 登录表单 */}
        <div className={`bg-white rounded-2xl shadow-form p-8 ${styles.formAnimation}`}>
          <div className="text-center mb-6">
            <h2 className="text-2xl font-semibold text-text-primary mb-2">欢迎回来</h2>
            <p className="text-text-secondary">请登录您的账户</p>
          </div>

          {/* 错误提示 */}
          {showErrorMessage && (
            <div className={`bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-4 ${styles.errorMessage}`}>
              <i className="fas fa-exclamation-circle mr-2"></i>
              <span>{errorText}</span>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* 账号输入框 */}
            <div className="space-y-2">
              <label htmlFor="username" className="block text-sm font-medium text-text-primary">
                邮箱/手机号
              </label>
              <div className="relative">
                <input 
                  type="text" 
                  id="username" 
                  name="username" 
                  value={formData.username}
                  onChange={handleInputChange}
                  onKeyPress={handleUsernameKeyPress}
                  onFocus={handleInputFocus}
                  className={`w-full pl-12 pr-4 py-3 border border-border-light rounded-lg ${styles.formInputFocus} transition-all duration-200`}
                  placeholder="请输入邮箱或手机号"
                  required
                  autoComplete="username"
                />
                <i className="fas fa-user absolute left-4 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
              </div>
            </div>

            {/* 密码输入框 */}
            <div className="space-y-2">
              <label htmlFor="password" className="block text-sm font-medium text-text-primary">
                密码
              </label>
              <div className="relative">
                <input 
                  type={showPassword ? 'text' : 'password'}
                  id="password" 
                  name="password" 
                  value={formData.password}
                  onChange={handleInputChange}
                  onKeyPress={handlePasswordKeyPress}
                  onFocus={handleInputFocus}
                  className={`w-full pl-12 pr-12 py-3 border border-border-light rounded-lg ${styles.formInputFocus} transition-all duration-200`}
                  placeholder="请输入密码"
                  required
                  autoComplete="current-password"
                />
                <i className="fas fa-lock absolute left-4 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
                <button 
                  type="button" 
                  onClick={handleTogglePassword}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary hover:text-text-primary transition-colors"
                >
                  <i className={`fas ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                </button>
              </div>
            </div>

            {/* 记住密码和忘记密码 */}
            <div className="flex items-center justify-between">
              <label className="flex items-center space-x-2 cursor-pointer">
                <input 
                  type="checkbox" 
                  name="rememberMe"
                  checked={formData.rememberMe}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-primary border-border-light rounded focus:ring-primary"
                />
                <span className="text-sm text-text-secondary">记住密码</span>
              </label>
              <Link to="/forgot-password" className={`text-sm text-primary ${styles.linkHover} transition-colors`}>
                忘记密码？
              </Link>
            </div>

            {/* 登录按钮 */}
            <button 
              type="submit" 
              disabled={isLoading}
              className={`w-full bg-primary text-white py-3 px-4 rounded-lg font-medium ${styles.btnPrimary} transition-all duration-200 flex items-center justify-center space-x-2 ${isLoading ? 'opacity-75 cursor-not-allowed' : ''}`}
            >
              <span>{isLoading ? '登录中...' : '登录'}</span>
              {isLoading && <i className="fas fa-spinner fa-spin"></i>}
            </button>
          </form>

          {/* 注册链接 */}
          <div className="text-center mt-6 pt-6 border-t border-border-light">
            <p className="text-text-secondary">
              还没有账户？
              <Link to="/register" className={`text-primary font-medium ${styles.linkHover} transition-colors ml-1`}>
                立即注册
              </Link>
            </p>
          </div>
        </div>

        {/* 页脚 */}
        <div className="text-center mt-8">
          <p className="text-sm text-text-secondary">
            © 2024 食算. 让健康饮食更简单
          </p>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;

